package cn.com.ghy.android.widget;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.ghy.android.bean.CustomerInfoBean;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.bean.MyWayBean;
import cn.com.ghy.android.bean.TaskBean;
import cn.com.ghy.android.bean.UnitInfoBean;
import cn.com.ghy.android.bean.VisitPlanBean;
import cn.com.ghy.android.bean.VisitPlanWorkTypeBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.LineOpeService;
import cn.com.ghy.android.service.NoteOpeService;
import cn.com.ghy.android.service.PlanOpeService;
import cn.com.ghy.android.service.VisitOpeService;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.util.CommonUtil;
import cn.com.ghy.android.widget.chat.CustomerList;
import cn.com.ghy.android.widget.coopvisit.CoopVisit;
import cn.com.ghy.android.widget.plan.VisitPlan;
import cn.com.ghy.android.widget.report.OrderReport;
import cn.com.ghy.android.widget.salemag.SaleManageOrder;
import cn.com.ghy.android.widget.set.PersonInfo;
import cn.com.ghy.android.widget.task.NewTask;
import cn.com.ghy.android.widget.visit.TodayVisit;
import cn.com.ghy.android.widget.way.MyWay;
import cn.com.ghy.android.widget.work.WorkReport;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:主菜单
 * @author wuz  @date 2011-5-4 13:25:34
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 */

public class Main extends Activity {

	private GridView gridView = null;
	private TextView labDisplayInfo = null;
	private ProgressDialog progressDialog = null;
	private Intent intent = null;
	private Bundle bundle = null;
	private ImageButton btnAbout = null;
	private ImageButton btnExit = null;
	private SimpleAdapter simpleAdapter = null;

	private LoginInfoBean loginInfo = null;
	private List<UnitInfoBean> listUnitInfo = null;
	private String newTaskRemind = null;

	private int[] mainMenuImageId = new int[] { R.drawable.visit, R.drawable.coopvisit,
			R.drawable.chat, R.drawable.report, R.drawable.way, R.drawable.plan, R.drawable.task,
			R.drawable.work, R.drawable.salemag, R.drawable.set
			, R.drawable.baidumap 
			};
	private int[] mainMenuStr = new int[] { R.string.visit, R.string.coopvisit, R.string.chat,
			R.string.report, R.string.way, R.string.plan, R.string.task, R.string.work,
			R.string.salemag, R.string.set
			,R.string.mapname 
			};

	private HttpThread httpThread = null;

	private DisposeException disposeException = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.main_menu);
		getSession();
		findView();
		createMainMenu();
		addListener();
	}

	@SuppressWarnings("unchecked")
	private void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		bundle = this.getIntent().getExtras();
		loginInfo = (LoginInfoBean) bundle.getSerializable("loginInfo");
		listUnitInfo = (List<UnitInfoBean>) bundle.getSerializable("listUnitInfo");
		newTaskRemind = bundle.getString("newTaskRemind");
		if (null != loginInfo && null != listUnitInfo && listUnitInfo.size() > 0
				&& null != newTaskRemind) {
			((ComStaticApp) this.getApplication()).setLoginInfo(loginInfo);
			((ComStaticApp) this.getApplication()).setListUnitInfo(listUnitInfo);
		} else {
			Toast.makeText(Main.this, "程序出现异常,请联系管理员!", Toast.LENGTH_LONG).show();
			Main.this.finish();
		}

		if ("Y".equals(newTaskRemind)) {
			Toast.makeText(Main.this, "您有最新任务,请及时处理!", Toast.LENGTH_LONG).show();
		}
	}

	private void findView() {
		gridView = (GridView) findViewById(R.id.mainMenu);
		labDisplayInfo = (TextView) findViewById(R.id.labTxtDisplayInfo);
		btnAbout = (ImageButton) findViewById(R.id.btnAbout);
		btnExit = (ImageButton) findViewById(R.id.btnExit);
	}

	private void createMainMenu() {
		labDisplayInfo.setText("你好,欢迎：" + loginInfo.getSaofname() + ",销售员：" + loginInfo.getDspname());
		labDisplayInfo.setTextSize(15);
		
		List<Map<String, Object>> listItem = new ArrayList<Map<String, Object>>();
		Map<String, Object> mapItem = null;
		for (int i = 0; i < mainMenuImageId.length; i++) {
			mapItem = new HashMap<String, Object>();
			mapItem.put("itemImage", mainMenuImageId[i]);
			mapItem.put("itemText", getResources().getString(mainMenuStr[i]));
			listItem.add(mapItem);
			mapItem = null;
		}

		simpleAdapter = new SimpleAdapter(Main.this, listItem, R.layout.menu_item, new String[] {
				"itemImage", "itemText" }, new int[] { R.id.itemImage, R.id.itemText });

		gridView.setAdapter(simpleAdapter);
	}

	private void addListener() {
		gridView.setOnItemClickListener(itemListener);
		btnAbout.setOnClickListener(btnListener);
		btnExit.setOnClickListener(btnListener);
	}

	private AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() {

		@SuppressWarnings("unchecked")
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			Map<String, Object> itemMap = (Map<String, Object>) parent.getItemAtPosition(position);
			switch (Integer.parseInt(itemMap.get("itemImage").toString())) {
				case R.drawable.chat :
					intent = new Intent(Main.this, CustomerList.class);
					Main.this.startActivity(intent);
					break;
				case R.drawable.report :
					intent = new Intent(Main.this, OrderReport.class);
					Main.this.startActivity(intent);
					break;
				case R.drawable.way :
					httpThread = new HttpThread(handler);
					httpThread.doStart(R.drawable.way);
					break;
				case R.drawable.task :
					httpThread = new HttpThread(handler);
					httpThread.doStart(R.drawable.task);
					break;
				case R.drawable.work :
					intent = new Intent(Main.this, WorkReport.class);
					Main.this.startActivity(intent);
					break;
				case R.drawable.plan :
					httpThread = new HttpThread(handler);
					httpThread.doStart(R.drawable.plan);
					break;
				case R.drawable.visit :
					httpThread = new HttpThread(handler);
					httpThread.doStart(R.drawable.visit);
					break;
				case R.drawable.set :
					intent = new Intent(Main.this, PersonInfo.class);
					Main.this.startActivity(intent);
					break;
				case R.drawable.coopvisit :
					intent = new Intent(Main.this, CoopVisit.class);
					Main.this.startActivity(intent);
					break;
				case R.drawable.salemag :
					intent = new Intent(Main.this, SaleManageOrder.class);
					Main.this.startActivity(intent);
					break;
//				case R.drawable.baidumap :
//					intent = new Intent(Main.this, BaiduMap.class);
////					intent = new Intent(Main.this, PersonInfo.class);
//					Main.this.startActivity(intent);
//					break;
			}
		}
	};

	private View.OnClickListener btnListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.btnAbout :
					intent = new Intent(Main.this, AboutSystem.class);
					Main.this.startActivity(intent);
					break;
				case R.id.btnExit :
					new AlertDialog.Builder(Main.this).setTitle("提示信息").setMessage("确定要退出系统?")
							.setPositiveButton("确定", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dlg, int sumthin) {
									ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
									am.restartPackage(getPackageName());
									finish();
								}
							}).setNeutralButton("取消", null).show();
					break;
			}

		}
	};

	private class HttpThread extends Thread {

		private Handler thread_handler = null;
		private int flag = -1;

		public HttpThread(Handler hander) {
			thread_handler = hander;
		}

		public void doStart(int flag) {
			this.flag = flag;
			progressDialog = new ProgressDialog(Main.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，Just a moment , please......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			this.start();
		}

		public void run() {
			Message message = null;
			message = thread_handler.obtainMessage();
			bundle = new Bundle();
			LineOpeService lineOpeService = null;
			List<MyWayBean> myWayList = null;
			List<TaskBean> taskBeanList = null;
			NoteOpeService noteOpeService = null;
			PlanOpeService planOpeService = null;
			List<VisitPlanWorkTypeBean> visitPlanWorkTypeList = null;
			List<VisitPlanBean> visitPlanList = null;
			String status = null;
			VisitOpeService visitOpeService = null;
			String taskStateStr = null;
			List<CustomerInfoBean> customerInfoList = null;
			try {
				switch (flag) {
					case R.drawable.way ://访问我的路线
						lineOpeService = new LineOpeService();
						myWayList = lineOpeService.LineList(loginInfo);
						progressDialog.dismiss();
						message.what = CommonStatic.STATE_NORMAL;
						bundle.putSerializable("myWayList", (Serializable) myWayList);
						bundle.putInt("flag", flag);
						break;
					case R.drawable.task :
						noteOpeService = new NoteOpeService();
						taskBeanList = noteOpeService.GetNewTask(loginInfo);
						progressDialog.dismiss();
						message.what = CommonStatic.STATE_NORMAL;
						bundle.putSerializable("taskBeanList", (Serializable) taskBeanList);
						bundle.putInt("flag", flag);
						break;
					case R.drawable.plan :
						String monthid = CommonUtil.nextMonthId();
						planOpeService = new PlanOpeService();
						status = planOpeService.GetPlanState(loginInfo, monthid);
						message.what = CommonStatic.STATE_NORMAL;
						visitPlanWorkTypeList = planOpeService.WorkTypeList();
						lineOpeService = new LineOpeService();
						myWayList = lineOpeService.LineList(loginInfo);
						if (CommonStatic.visitPlan_N.equals(status)) {
							progressDialog.dismiss();
							bundle.putSerializable("visitPlanWorkTypeList",
									(Serializable) visitPlanWorkTypeList);
							bundle.putSerializable("myWayList", (Serializable) myWayList);
							bundle.putString("visitPlanStatus", status);
							bundle.putString("monthid", monthid);
							bundle.putInt("flag", flag);
						} else {
							visitPlanList = planOpeService.GetPlan(loginInfo, monthid);
							progressDialog.dismiss();
							bundle.putSerializable("visitPlanWorkTypeList",
									(Serializable) visitPlanWorkTypeList);
							bundle.putSerializable("visitPlanList", (Serializable) visitPlanList);
							bundle.putSerializable("myWayList", (Serializable) myWayList);
							bundle.putString("visitPlanStatus", status);
							bundle.putString("monthid", monthid);
							bundle.putInt("flag", flag);
						}
						break;
					case R.drawable.visit :
						visitOpeService = new VisitOpeService();
						taskStateStr = visitOpeService.GetTaskState(loginInfo);
						message.what = CommonStatic.STATE_NORMAL;
						bundle.putString("taskStateStr", taskStateStr);
						if (!"".equals(taskStateStr)) {
							customerInfoList = visitOpeService.GetTaskDetail(loginInfo);
							bundle.putSerializable("customerInfoList",
									(Serializable) customerInfoList);
						}
						progressDialog.dismiss();
						bundle.putInt("flag", flag);
						break;
				}
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
			message.setData(bundle);
			thread_handler.sendMessage(message);//将Message对象加入到消息队列当中 
		}
	}
	
	//使用匿名内部类来复写Handler当中的handlerMessage()方法
	private Handler handler = new Handler() {
		int flag = -1;

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message message) {
			flag = message.getData().getInt("flag");
			List<MyWayBean> myWayList = null;
			List<TaskBean> taskBeanList = null;
			List<VisitPlanWorkTypeBean> visitPlanWorkTypeList = null;
			List<VisitPlanBean> visitPlanList = null;
			List<CustomerInfoBean> customerInfoList = null;
			String status = null;
			String monthid = null;
			String taskStateStr = null;
			String[] taskStateStrArr = null;
			switch (message.what) {
				case CommonStatic.STATE_NORMAL :
					switch (flag) {
						case R.drawable.way :
							myWayList = (List<MyWayBean>) message.getData().getSerializable("myWayList");
							/*if (myWayList.size() == 0) {
								new AlertDialog.Builder(Main.this).setTitle("提示信息")
										.setMessage("没有有效的路线信息,请联系销售支持进行维护!")
										.setNeutralButton("关闭", null).show();
								break;
							}*/
							//模拟我的路线数据
							MyWayBean myWayBean = new MyWayBean();
							myWayBean.setWayid("0001");
							myWayBean.setWayname("去沃尔玛路线");
							/*CustomerInfoBean customerInfoBean = new CustomerInfoBean();
							customerInfoBean.setCapacity("capacity");
							customerInfoBean.setCityname("苏州");
							customerInfoBean.setCk1name("ck1name");
							customerInfoBean.setName_org1("name_org1");
							customerInfoBean.setJxsname("jxsname");
							customerInfoBean.setZonename("zonename");
							myWayBean.setCustomerInfoList(customerInfoList);*/
							myWayList.add(myWayBean);
							bundle = new Bundle();
							bundle.putSerializable("myWayList", (Serializable) myWayList);
							intent = new Intent(Main.this, MyWay.class);
							intent.putExtras(bundle);
							Main.this.startActivity(intent);
							break;
						case R.drawable.task :
							taskBeanList = (List<TaskBean>) message.getData().getSerializable(
									"taskBeanList");
							bundle = new Bundle();
							bundle.putSerializable("taskBeanList", (Serializable) taskBeanList);
							intent = new Intent(Main.this, NewTask.class);
							intent.putExtras(bundle);
							Main.this.startActivity(intent);
							break;
						case R.drawable.plan :
							visitPlanWorkTypeList = (List<VisitPlanWorkTypeBean>) message.getData()
									.getSerializable("visitPlanWorkTypeList");
							myWayList = (List<MyWayBean>) message.getData().getSerializable("myWayList");
							visitPlanList = (List<VisitPlanBean>) message.getData().getSerializable(
									"visitPlanList");
							status = (String) message.getData().getString("visitPlanStatus");
							monthid = (String) message.getData().getString("monthid");
							bundle = new Bundle();
							bundle.putSerializable("visitPlanWorkTypeList",
									(Serializable) visitPlanWorkTypeList);
							bundle.putSerializable("visitPlanList", (Serializable) visitPlanList);
							bundle.putSerializable("myWayList", (Serializable) myWayList);
							bundle.putString("visitPlanStatus", status);
							bundle.putString("monthid", monthid);
							intent = new Intent(Main.this, VisitPlan.class);
							intent.putExtras(bundle);
							Main.this.startActivity(intent);
							break;
						case R.drawable.visit :
							taskStateStr = message.getData().getString("taskStateStr");
							if ("".equals(taskStateStr)) {
								new AlertDialog.Builder(Main.this).setTitle("提示信息")
										.setMessage("今天没有拜访计划!").setNeutralButton("关闭", null)
										.show();
							} else {
								customerInfoList = (List<CustomerInfoBean>) message.getData()
										.getSerializable("customerInfoList");
								taskStateStrArr = taskStateStr.split("\\|\\|\\|");
								bundle = new Bundle();
								bundle.putStringArray("taskStateStrArr", taskStateStrArr);
								bundle.putSerializable("customerInfoList",
										(Serializable) customerInfoList);
								intent = new Intent(Main.this, TodayVisit.class);
								intent.putExtras(bundle);
								Main.this.startActivity(intent);
							}
							break;
					}
					break;
			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(Main.this).setTitle("提示信息").setMessage("确定要退出系统?")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dlg, int sumthin) {
							ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
							am.restartPackage(getPackageName());
							finish();
						}
					}).setNeutralButton("取消", null).show();
		}
		return true;
	}
}
